﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TbShop.Entity;
using TbShop.Web.Helpers;
using TbShop.Web.Infrastructure.Tbk;
using TbShop.Web.Models;

namespace TbShop.Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            int categoryId = 0;
            int.TryParse(Request.QueryString["categoryId"], out categoryId);
            string keyword = Request.QueryString["keyword"];
            if (string.IsNullOrEmpty(keyword) && categoryId == 0)
            {
                categoryId = 1;
            }
            var category = CacheHelper<TbCategory>.GetById(categoryId);
            var parentCategoryId = categoryId;
            if (categoryId > 0)
            {
                if (category != null && category.ParentId > 0)
                    parentCategoryId = category.ParentId;
            }

            HomeModel model = new HomeModel();
            if (parentCategoryId > 0)
            {
                model.Categorys = CacheHelper<TbCategory>.GetAll().Where(p => p.ParentId == parentCategoryId);
            }
            model.CurrentCategory = CacheHelper<TbCategory>.GetById(parentCategoryId);
            model.SubCategory = category;
            model.Goods = TBKHelper.GetTBKGoods(string.IsNullOrEmpty(keyword) ? category.TbSearch : keyword, "", "", 1, 20);
            return View(model);
        }

        public string LoadMoreData(int categoryId, int pageIndex)
        {
            string keyword = Request.QueryString["keyword"];
            TbCategory category = null;
            if (categoryId != 0)
            {
                category = CacheHelper<TbCategory>.GetById(categoryId);
            }
            var data = TBKHelper.GetTBKGoods(string.IsNullOrEmpty(keyword) ? category.TbSearch : keyword, "", "", pageIndex, 20);
            return JsonConvert.SerializeObject(data);
        }
    }
}